/**
 *
 */

var app = angular.module('fiveApp.directives', []);

app.directive('datetimepicker', [function () {
    return {
        //require : '?ngModel',
        restrict: 'A',
        scope: {
            ngModel: '=',
        },
        link: function (scope, element, attr, ngModel) {
            /*ngModel.$render = function(){
                element.val(ngModel.$viewValue || '');
            }*/
            //element.val(scope.ngModel);
            element.datetimepicker({
                format: attr.formate || 'Y-m-d', //格式化时间
                timepicker: attr.time || false,
                onSelectDate: function (dateText) {
                    console.log(element.val())
                },
                minDate: '2005/06/01'
            });
            $.datetimepicker.setLocale('ch')
        }
    }
}])

app.directive('noData', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            noData: '=',
        },
        link: function (scope, element, attr) {
            var createHtml = function () {
                if (scope.noData.length == 0) {
                    var html = "<td colspan='" + element.parents('table').find('td').length + "'>暂无数据</td>";
                    element.html(html);
                } else {
                    element.html('');
                }
            }
            scope.$watch('noData', function (rel) {
                createHtml();
            })
        }
    };
}])

app.directive('mobileSelect', [function () {
    return {
        restrict: 'A',
        scope: {
            ngModel: '=',
            mobileSelect: '=',
            children: '='
        },
        link: function (scope, element, attr) {
            var setData = function (data) {
                scope.$apply(function () {
                    scope.ngModel = data
                })
            }
            console.log(attr.id)
            var select = new MobileSelect({
                trigger: '#' + attr.id,
                title: attr.title || '选择',
                wheels: [
                    {data: scope.mobileSelect}
                ],
                position: [0, 1],
                transitionEnd: function (indexArr, data) {
                    console.log(data)
                },
                callback: function (indexArr, data) {
                    if (data['0']['id'] && data['1']['id']) {
                        setData(data['0']['id'] + '-' + data['1']['id']);
                    }else if(data[0]){
                        setData(data[0])
                    }
                }
            })
        }
    }
}])

app.directive('uploadImg', [function () {
    return {
        restrict: 'A',
        scope: {
            imgArr: '=',
            maxNum: '@'
        },
        template: `<div class="post_sc_son_box l">
						<div class="post_sc_son" ng-repeat="img in imgArr">
							<img ng-src="{{img}}" alt="">
						</div>
						<div class="post_sc_son_sc l"  ng-click="select()">
							<img src="/static/index/images/index_img2.png" alt="">
							<input type="file" accept="image/*" style="display: none" class="uploadImg">
						</div>
					</div>`,
        link: function (scope, element, attr) {
            scope.select = function () {
                element.find('.uploadImg').click();
            }
            element.find('.uploadImg').change(function (e) {
                var file = e.target.files['0'];
                if (file.size / 1024 / 1024 > 4) {
                    alert('图片太大了，请选择小于4M的图片');
                    element.find('.uploadImg').val('');
                    return;
                }
                var fr = new FileReader();
                fr.readAsDataURL(file);
                fr.onload = function (rel) {
                    var base64Data = rel.currentTarget.result;
                    scope.$apply(function () {
                        scope.imgArr.push(base64Data);
                    })
                }
            })
        },
        replace: true
    }
}])


app.directive('docScrollTop', ['$timeout', function ($timeout) {
    return {
        restrict: "A",
        scope: {
            docScrollTop: '=', //回调方法
            page: '=',
            pages: '='
        },
        link: function (scope, element, attr) {
            element['0'].addEventListener('scroll', function () {
                var doc = element['0'];
                if (doc.clientHeight + doc.scrollTop >= doc.scrollHeight - 2) {
                    if (scope.pages > scope.page) {
                        scope.$apply(function () {
                            scope.page += 1;
                            $timeout(function () {
                                scope.docScrollTop();
                            })
                        })
                    }
                }
            })
            scope.$on('$destroy', function () {
                window.removeEventListener('scroll', function () {
                })
            })
        }
    }
}])

app.directive('docScrollTop2', ['$timeout', function ($timeout) {
    return {
        restrict: "A",
        scope: {
            docScrollTop2: '=', //回调方法
            page: '=',
            pages: '=',
            loading:'='
        },
        link: function (scope, element, attr) {
            window.addEventListener('scroll', function () {
                let clientHeight = document.documentElement.clientHeight; //浏览器高度
                let scrollHeight = document.body.scrollHeight;
                let scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
                let distance = 150; //距离视窗还用50的时候，开始触发；
                // $('#console').text(scrollTop +'++'+ clientHeight +'++'+ scrollHeight )
                if ((scrollTop + clientHeight) >= (scrollHeight - distance) && scope.loading) {
                    if (scope.pages > scope.page){
                        scope.$apply(function () {
                            scope.page += 1;
                            $timeout(function () {
                                scope.docScrollTop2();
                            })
                        })
                    }
                }
            })

            scope.$on('$destroy', function () {
                window.removeEventListener('scroll', function () {
                })
            })
        }
    }
}])
app.directive('indexPage', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            indexPage: '=',   //总页数
            currPage: '=',    //当前页
            datasCount: '=',  //总条数
            callback: '=',     //回调
            noInit: '@',
        },
        link: function (scope, element, attr) {

            scope.page = function (page) {
                var pages = scope.indexPage;
                page < 1 && (page = 1);
                page > pages && (page = pages);
                page == 0 && (page = 1);
                scope.currPage = page;
                scope.goPage = scope.currPage;

                if (scope.callback) {
                    setTimeout(function () {
                        scope.callback();
                    }, 100)
                }
                element.html($compile(createTemplate())(scope));
            }
            scope.$watch('indexPage', function (val) {
                //if(scope.datasCount){
                element.html($compile(createTemplate())(scope));
                //}
            })

            var createTemplate = function () {
                var pages = scope.indexPage;
                var page = scope.currPage;

                var max_button = attr.pageButton || 10;
                var html = '';
                if (pages > 1) {
                    html = '<div class="common-page">' +
                        '<div class="item mdBtn first" ng-click="page(1)"><img src="/static/index/images/page-first.png" alt=""></div>'
                        +'<div class="item mdBtn prev" ng-click="page(' + (scope.currPage - 1) + ')"><img src="/static/index/images/page-prev.png" alt=""></div>';
                    var num = 0;
                    var start = page < 5 ? 1 : page - 5;
                    if (start < 1)
                        start = 1;

                    var end = start + max_button;
                    end > pages && (end = pages);
                    for (var i = start; i <= end; i++) {
                        if (num < max_button) {
                            html += '<div class="item mdBtn btn" ng-click="page(' + i + ')">' + i + '</div>';
                            num++;
                        }
                    }
                    html += '<div class="item mdBtn next" ng-click="page(' + (scope.currPage + 1) + ')"><img src="/static/index/images/page-next.png" alt=""></div>';
                    html += '<div class="item mdBtn end" ng-click="page(' + pages + ')"><img src="/static/index/images/page-last.png" alt=""></div>';
                    html += '</div>';
                }

                return html;
            }

            if (!scope.noInit) {
                scope.page(scope.currPage || 1);
            } else {
                createTemplate();
            }
            //scope.page(1);
        },
        replace: true,
    };
});
